package linz

import kotlin.concurrent.thread

fun main() {

    //TODO 自定义Apply
    "Derry".apply {
        println(this)
    }.apply {

    }.apply {  }
    "OK".myApply {
        println(this)
    }

    //TODO 自定义let
    // TODO 官方的：
    val r : Float = "Derry".let {
        it

        ""
        true
        9
        4354.545f
    }

    // 我们自己写一套
    val r2 : Boolean = "Derry".mLet {
        println("我的值是：$it")

        false
    }
    println(r2)

    thread {
        println("我是异步线程")
    }

    mThread(true,"my-Thread") {
        println("我是异步线程！！ ${Thread.currentThread().name}")
    }

    // TODO repeat
    // TODO 官方的：
    repeat(10) {
        print("下标是:$it ")
    }

    println()

    // TODO 我们自己手写
    mRepeat(10) {
        print("下标是:$it ")
    }

    println()

    10.mRepeat2 {
        print("下标是:$it ")
    }

}



private inline fun mRepeat(count:Int,action:(Int) -> Unit){
    for (item in 0 until count) action(item)
}

private inline fun Int.mRepeat2(action: (Int) -> Unit){
    for (item in 0 until this) action(item)
}

private inline fun <I,O> I.mLet(lambda: (I) -> O) = lambda(this)

private inline fun <I> I.myApply(lambda:I.()->Unit) :I {
    lambda()
    return this
}

private /*inline*/  fun mThread(
    start: Boolean = true, name: String? = null,
    /*crossinline*/ runAction: () -> Unit
): Thread { // crossinline 这个 lambda 不要给我内联
    val thread = object : Thread() {
        override fun run() {
            super.run()
            runAction()
        }
    }

    name?.let { thread.name = name }
    if (start) thread.start()

    return thread
}